import express, { request } from 'express'
import { addSql, getResult, listSql } from '../../util/operateSql.js';
import http from '../../util/request.js';
import { sleep } from '../../util/common.js';
var router = express.Router();

router.get('/request',(req,res,next) => {
  http('https://reqres.in/api/users?page=2').then((result) => {
    
    res.send(result)
  }).catch((err) => {
    
  });
})

router.post('/copy', (req, res, next) => {
  const body = req.body.map(e => {
    return {
      weId: e?.id,
      ...e.payload
    }
  })
  body.forEach((e,index) => {
    const sql = addSql('wechat_bot.bot_user',e)    
    getResult(sql).then((result) => {
      if (index === body.length) {
        res.json(req.app.locals.success(result))      
      }
    }).catch((err) => {
      res.json(req.app.locals.error(err,`---第${index}条数据出错`))
    });
  });
})

router.post('/handleSpu',async (req,res,next) => {
	const getSql = listSql('resource.zhongcaoyao',{},{hasPage: false})
	const rows = await getResult(getSql)
	console.log('rows: ', rows.length);

	rows.forEach(async (row,index) => {
		const rich_text = row.rich_text.replace(/data-wuqianyan/g,'src')
		let imgs = rich_text.match(/<img src="(.*?)"/g)
		imgs instanceof Array && imgs.forEach((e,index) => {
			imgs[index] = imgs[index].replace(/<img src="(.*?)"/g,'$1')
		})
		imgs = imgs && imgs.join()
		
		const updateSql = `update t_spu set rich_text = '${rich_text}' , ${imgs? `img_url = '${imgs}'`  : '' } where title = '${row.title}'`
		await sleep(400 * index)
		await getResult(updateSql)
		console.log('title: ', row.title);
		console.log('imgs: ', imgs);
		console.log(`第${index+0}修改成功`);
	})

})

export default router